# Maintainer: Konstantin Podsvirov <konstantin@podsvirov.su>

_realName=mdBook
_realname=${_realName,,}
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=0.4.50
pkgrel=1
pkgdesc="Create book from markdown files, like Gitbook but implemented in Rust (mingw-w64)"
arch=('any')
mingw_arch=('mingw64' 'ucrt64' 'clang64' 'clangarm64')
url="https://rust-lang.github.io/mdBook/"
msys2_repository_url="https://github.com/rust-lang/mdBook"
msys2_references=(
  'archlinux: mdbook'
  "cpe: cpe:/a:rust-lang:mdbook"
  'purl: pkg:cargo/mdbook'
)
license=('spdx:MPL-2.0')
makedepends=("${MINGW_PACKAGE_PREFIX}-rust")
optdepends=("${MINGW_PACKAGE_PREFIX}-mdbook-pikchr: To render pikchr code blocks as image")
source=("$msys2_repository_url/archive/v$pkgver/$_realName-$pkgver.tar.gz")
sha256sums=('2d86ec7769f4ff3068e86a9bbc46bec4f0b78cffb6021dd24c82a4d44b5d27f6')

prepare() {
  cd "${srcdir}/${_realName}-${pkgver}"

  cargo fetch --locked --target "$(rustc -vV | sed -n 's/host: //p')"
}

build() {
  cd "${srcdir}"
  rm -rf "build-${MSYSTEM}" | true
  cp -r "${_realName}-${pkgver}" "build-${MSYSTEM}"
  cd "build-${MSYSTEM}"

  WINAPI_NO_BUNDLED_LIBRARIES=1 \
  "${MINGW_PREFIX}/bin/cargo.exe" build \
    --release \
    --frozen

  mkdir completions | true
  "./target/release/${_realname}.exe" completions bash > "completions/${_realname}.bash"
  "./target/release/${_realname}.exe" completions fish > "completions/${_realname}.fish"
  "./target/release/${_realname}.exe" completions zsh > "completions/_${_realname}"

  msg "Build documentation"
  cd guide

  "../target/release/${_realname}.exe" build
}

check() {
  cd "${srcdir}/build-${MSYSTEM}"

  "${MINGW_PREFIX}/bin/cargo.exe" test \
    --release \
    --frozen
}

package() {
  cd "${srcdir}/build-${MSYSTEM}"

  install -Dm755 "target/release/${_realname}.exe" "${pkgdir}${MINGW_PREFIX}/bin/${_realname}.exe"
  install -Dm644 "completions/${_realname}.bash" "${pkgdir}${MINGW_PREFIX}/share/bash-completion/completions/${_realname}"
  install -Dm644 "completions/${_realname}.fish" -t "${pkgdir}${MINGW_PREFIX}/share/fish/vendor_completions.d"
  install -Dm644 "completions/_${_realname}" -t "${pkgdir}${MINGW_PREFIX}/share/zsh/site-functions"
  install -d "${pkgdir}${MINGW_PREFIX}/share/doc/${_realname}"
  cp -a "guide/book" "${pkgdir}${MINGW_PREFIX}/share/doc/${_realname}/html"
  install -Dm644 "LICENSE" "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE"
}
